from database_manager import db_manager
from datetime import datetime, timedelta
from display_formatter import DisplayFormatter


class ViewController:
    def __init__(self, view):
        self.view = view

    def on_view_clicked(self):
        """处理查看信息按钮点击事件：显示详细的人脸信息统计"""
        if hasattr(self.view, 'reset_camera_and_controls'):
            self.view.reset_camera_and_controls()
        
        # 使用格式化工具创建标题
        header = DisplayFormatter.create_header("📊 人脸信息统计报告")
        self.view.update_display(header)
        
        try:
            # 获取人脸列表
            rows = db_manager.get_face_list()
            if not rows:
                empty_messages = DisplayFormatter.create_empty_state_message('no_faces')
                for msg in empty_messages:
                    self.view.update_display(msg)
                return
            
            # 计算统计数据
            total_count = len(rows)
            today_count, week_count, month_count = self._calculate_time_statistics(rows)
            
            # 显示统计摘要
            summary_lines = DisplayFormatter.format_statistics_summary(
                total_count, today_count, week_count, month_count
            )
            for line in summary_lines:
                self.view.update_display(line)
            self.view.update_display("")
            
            # 显示详细人员列表
            section_header = DisplayFormatter.create_section_header("👤 已录入人员详细列表")
            self.view.update_display(section_header)
            
            for i, (name, created_at) in enumerate(rows, 1):
                # 获取该人员的考勤统计
                attendance_stats = self._get_person_attendance_stats(name)
                
                # 格式化人员信息
                person_lines = DisplayFormatter.format_person_info(
                    name, created_at, attendance_stats, i
                )
                for line in person_lines:
                    self.view.update_display(line)
                self.view.update_display("")
            
            # 显示完成信息
            completion_header = DisplayFormatter.create_header("✅ 信息查询完成", 50, '=')
            self.view.update_display(completion_header)
            
        except Exception as e:
            self.view.update_display(f"❌ 查询人脸信息失败: {str(e)}")
    
    def _calculate_time_statistics(self, rows):
        """计算时间统计数据"""
        today_count = 0
        week_count = 0
        month_count = 0
        now = datetime.now()
        
        for name, created_at in rows:
            try:
                created_time = datetime.strptime(created_at, '%Y-%m-%d %H:%M:%S')
                if created_time.date() == now.date():
                    today_count += 1
                if created_time >= now - timedelta(days=7):
                    week_count += 1
                if created_time >= now - timedelta(days=30):
                    month_count += 1
            except ValueError:
                continue
        
        return today_count, week_count, month_count
    
    def _get_person_attendance_stats(self, name):
        """获取个人考勤统计信息"""
        try:
            # 获取最近30天的考勤记录
            records = db_manager.get_person_attendance_records(name, 30)
            if not records:
                return "暂无考勤记录"
            
            # 统计上班和下班次数
            clock_in_count = sum(1 for _, action, _ in records if action == 'in')
            clock_out_count = sum(1 for _, action, _ in records if action == 'out')
            
            # 获取最后一次考勤时间
            last_record = records[0] if records else None
            if last_record:
                _, last_action, last_time = last_record
                action_text = "上班" if last_action == 'in' else "下班"
                return f"上班{clock_in_count}次, 下班{clock_out_count}次, 最后{action_text}: {last_time}"
            
            return f"上班{clock_in_count}次, 下班{clock_out_count}次"
            
        except Exception:
            return "考勤统计获取失败"